﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace GW2LastOnline.Services
{
    public class Account
    {
        private const string LOGIN_URL = "https://account.guildwars2.com/login?redirect_uri=http%3A%2F%2Fleaderboards.guildwars2.com%2Fauthenticate%3Fsource%3D%252Fen%252Fna&&game_code=gw2";
        private const string LOGOUT_URL = "https://account.guildwars2.com/logout";
        private const string REFERER_URL = "https://leaderboards.guildwars2.com/login";
        private const string ACCOUNT_URL = "https://account.guildwars2.com/";

        public static CookieCollection Login(string username, string password)
        {
            HttpWebRequest request;
            HttpWebResponse response;
            Stream stream;

            username = Uri.EscapeDataString(username);
            password = Uri.EscapeDataString(password);

            byte[] formData = Encoding.ASCII.GetBytes("email=" + username + "&password=" + password);

            request = (HttpWebRequest)HttpWebRequest.Create(LOGIN_URL);
            request.AllowAutoRedirect = false;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = formData.Length;
            request.Referer = request.RequestUri.AbsoluteUri;
            request.CookieContainer = new CookieContainer();

            stream = request.GetRequestStream();
            stream.Write(formData, 0, formData.Length);
            stream.Close();

            response = (HttpWebResponse)request.GetResponse();

            string cookie = response.Headers[HttpResponseHeader.SetCookie];
            int i;

            response.Close();

            if (cookie != null && (i = cookie.IndexOf("s=")) >= 0)
            {
                string value = cookie.Substring(i + 2, cookie.IndexOf(';', i) - i - 2);

                CookieCollection cookies = new CookieCollection();
                cookies.Add(new Cookie("s", value, "/", ".guildwars2.com")); //session key
                cookies.Add(new Cookie("initialRedirect", "true", "/", ".guildwars2.com")); //to prevent forced redirect on first visited page

                Console.WriteLine("Session key: " + value);

                return cookies;
            }
            else
            {
                return null;
            }
        }

        public static CookieCollection Login(string sessionKey)
        {
            HttpWebRequest request;
            HttpWebResponse response;

            CookieCollection cookies = new CookieCollection();
            cookies.Add(new Cookie("s", sessionKey, "/", ".guildwars2.com")); //session key
            cookies.Add(new Cookie("initialRedirect", "true", "/", ".guildwars2.com")); //to prevent forced redirect on first visited page

            request = (HttpWebRequest)HttpWebRequest.Create(ACCOUNT_URL);
            request.AllowAutoRedirect = false;
            request.Method = "GET";
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(cookies);

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                response.Close();
            }
            catch
            {
                return null;
            }

            //expected response is either a redirect to the account page if successful, or login if failed

            string location = response.Headers[HttpResponseHeader.Location];

            if (location.ToLower() == "account")
                return cookies;

            return null;
        }

        public static void Logout(CookieCollection cookies)
        {
            HttpWebRequest request;
            HttpWebResponse response;

            request = (HttpWebRequest)HttpWebRequest.Create(LOGOUT_URL);
            request.AllowAutoRedirect = false;
            request.Method = "GET";
            request.CookieContainer = new CookieContainer();
            foreach (Cookie c in cookies)
                request.CookieContainer.Add(c);
            //request.CookieContainer.Add(cookies);

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                response.Close();
            }
            catch
            {
            }
        }
    }
}
